

package com.xgit.iov.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xgit.iov.admin.execl.UserExcel;
import com.xgit.iov.admin.service.SysUserService;
import com.xgit.iov.common.core.entity.SysUser;
import com.xgit.iov.common.core.util.ExcelUtil;
import com.xgit.iov.common.core.util.R;
import com.xgit.iov.common.core.util.SecurityUtils;
import com.xgit.iov.common.log.annotation.LogAnnotation;
import com.xgit.iov.common.security.annotation.Inner;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lengleng
 * @date 2019/2/1
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
@Api(value = "user", tags = "用户管理模块")
public class UserController {

	private final SysUserService userService;

	/**
	 * 获取当前用户全部信息
	 *
	 * @return 用户信息
	 */
	@GetMapping(value = {"/info"})
	public R info() {
		String username = SecurityUtils.getUser().getUsername();
		SysUser user = userService.getOne(Wrappers.<SysUser>query()
			.lambda().eq(SysUser::getUsername, username));
		if (user == null) {
			return R.failed("获取当前用户信息失败");
		}
		return R.ok(userService.getUserInfo(user));
	}

	/**
	 * 获取指定用户全部信息
	 *
	 * @return 用户信息
	 */
	@Inner
	@GetMapping("/info/{username}")
	public R info(@PathVariable String username) {
		SysUser user = userService.getOne(Wrappers.<SysUser>query()
			.lambda().eq(SysUser::getUsername, username));
		if (user == null) {
			return R.failed(String.format("用户信息为空 %s", username));
		}
		return R.ok(userService.getUserInfo(user));
	}

	/**
	 * 通过ID查询用户信息
	 *
	 * @param id ID
	 * @return 用户信息
	 */
	@GetMapping("/{id}")
	public R user(@PathVariable Long id) {
		return R.ok(userService.getUserVoById(id));
	}

	/**
	 * 根据用户名查询用户信息
	 *
	 * @param username 用户名
	 * @return
	 */
	@GetMapping("/details/{username}")
	public R user(@PathVariable String username) {
		SysUser condition = new SysUser();
		condition.setUsername(username);
		return R.ok(userService.getOne(new QueryWrapper<>(condition)));
	}

	/**
	 * 删除用户信息
	 *
	 * @param ids ID
	 * @return R
	 */
	@LogAnnotation(value="删除用户信息")
	@DeleteMapping("/{ids}")
	@PreAuthorize("@pms.hasPermission('sys_user_del')")
	public R userDel(@PathVariable Long[] ids) {
		for (Long userId : ids){
			SysUser sysUser = userService.getById(userId);
			userService.removeUserById(sysUser);
		}
		return R.ok(Boolean.TRUE);
	}

	/**
	 * 添加用户
	 *
	 * @param sysUser 用户信息
	 * @return success/false
	 */
	@LogAnnotation("添加用户")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('sys_user_add')")
	public R user(@RequestBody SysUser sysUser) {
		return R.ok(userService.saveUser(sysUser));
	}

	/**
	 * 更新用户信息
	 *
	 * @param sysUser 用户信息
	 * @return R
	 */
	@LogAnnotation("更新用户信息")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('sys_user_edit')")
	public R updateUser(@Valid @RequestBody SysUser sysUser) {
		return R.ok(userService.updateUser(sysUser));
	}

	/**
	 * 分页查询用户
	 *
	 * @param page    参数集
	 * @param sysUser 查询参数列表
	 * @return 用户集合
	 */
	@GetMapping("/page")
	public R getUserPage(Page page, SysUser sysUser) {
		return R.ok(userService.getUserWithRolePage(page, sysUser));
	}

	/**
	 * 修改个人信息
	 *
	 * @param sysUser
	 * @return success/false
	 */
	@LogAnnotation("修改个人信息")
	@PutMapping("/edit")
	public R updateUserInfo(@Valid @RequestBody SysUser sysUser) {
		return R.ok(userService.updateUserInfo(sysUser));
	}

	@PostMapping("/reset-password")
	@LogAnnotation(value = "初始化密码")
	public R resetPassword(@RequestParam Long[] ids) {
		boolean temp = userService.resetPassword(ids);
		return R.ok(temp);
	}

	/**
	 * @param username 用户名称
	 * @return 上级部门用户列表
	 */
	@GetMapping("/ancestor/{username}")
	public R listAncestorUsers(@PathVariable String username) {
		return R.ok(userService.listAncestorUsersByUsername(username));
	}

	/**
	 * 导入数据
	 */
	@LogAnnotation("导入数据")
	@PostMapping("import")
	public R importExcl(MultipartFile file) {
		String filename = file.getOriginalFilename();
		if (StringUtils.isEmpty(filename)) {
			throw new RuntimeException("请上传文件!");
		}
		if ((!StringUtils.endsWithIgnoreCase(filename, ".xls") && !StringUtils.endsWithIgnoreCase(filename, ".xlsx"))) {
			throw new RuntimeException("请上传正确的excel文件!");
		}
		String msg = "操作成功";
		try {
			List<UserExcel> userExcelList = ExcelUtil.importExcel(file, 0, 1, UserExcel.class);
			if (userExcelList.size() > 0) {
				msg = userService.importUsers(userExcelList);
			}
		} catch (Exception e) {
			msg = "导入数据失败！失败信息："+e.getMessage();
			e.printStackTrace();
		}
		return R.ok(msg);
	}


	/**
	 * 导出模板
	 */
	@GetMapping("import/template")
	public void importFileTemplate(HttpServletResponse response) {
		List<UserExcel> list = new ArrayList<>();
		try {
			ExcelUtil.exportExcel(list, null, "用户数据模板", UserExcel.class, "用户数据模板", response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导出数据
	 * @return
	 */
	@GetMapping("/export")
	public void export(SysUser sysUser, HttpServletResponse response) {
		List<UserExcel> result = userService.exportUsers(sysUser);
		//导出操作
		try {
			ExcelUtil.exportExcel(result, null, "用户数据", UserExcel.class, "用户数据", response);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
